<?php
namespace backend\models;

use Yii;
use yii\base\Model;
use yii\base\Exception;
use common\models\Process;
use common\models\Department;

class ProcessForm extends Model
{
	public $tran_depart;
	public $undertake_depart;
	public $order;
	public $id;
	public $pcode;
	public $new_process;
	public $control;

	private $_process;

	public function __construct($id=null, $config = [])
	{
		if (!empty($id)) {
			$process = Process::findOne($id);
			$this->tran_depart = $process->tran_depart;
			$this->undertake_depart = $process->undertake_depart;
			$this->id = $process->id;
			$this->order = $process->id;
		} else {
			$process = new Process;
		}
		$this->_process = $process;

		return parent::__construct($config);
	}

	public function formName()
    {
        return '';
    }

	public function rules()
	{
		return [
			[['tran_depart', 'undertake_depart'], 'required'],
			[['tran_depart', 'undertake_depart'], 'validateProcess'],
			[['order', 'new_process', 'pcode', 'control'], 'safe']
		];
	}

	public function validateProcess($attribute, $params)
	{
		if (!$this->hasErrors()) {
			if ($this->tran_depart == $this->undertake_depart) {
				$this->addError($attribute, '转接部门与承接部门不能相同');
			}
			$process = Process::find()->where(['tran_depart' => $this->tran_depart, 'undertake_depart' => $this->undertake_depart, 'pcode' => $this->pcode])->one();
			if ($process) {
				$this->addError($attribute, '此流程已经存在');
			}
			$tran_depart = Department::findOne($this->tran_depart);
			$undertake_depart = Department::findOne($this->undertake_depart);
			if ($tran_depart->pid == 0 || $undertake_depart->pid == 0) {
				$this->addError($attribute, '顶级部门不能加入流程');
			}
		}
	}

	public function addOrUpdate()
	{
		$process = $this->_process;
		if ($this->pcode) {
			$process->pcode = $this->pcode;
			$process->name = Process::find()->where(['pcode' => $this->pcode])->one()->name;
		}
		if ($this->new_process) {
			$process->pcode = md5(uniqid().'_'.time());
			$process->name = $this->new_process;
		}
		if ($this->control) {
			$control = "";
			foreach ($this->control as $val) {
				$control .= $val . ',';
			}
			$process->control = trim($control, ',');
		}
		$process->tran_depart = $this->tran_depart;
		$process->undertake_depart = $this->undertake_depart;
		$process->status = Process::ACTIVE_STATUS;
		if ($process->save(false)) {

			return true;
		} else {

			return false;
		}
	}


}	